﻿// Auto complete tagging with commas.

(function ($) {
    function split(val){
        return val.split(/,\s*/);
    }
    function extractLast(term){
        return split(term).pop();
    }
    $.fn.multipleAutoComplete = function(){
        $(this).each(function(){
            var elem = $(this);
            elem.autocomplete({
                source: function (request, response) {
                    $.getJSON(elem.attr("ref"), { term: extractLast(request.term) }, response);
                },
                search: function () {
                    var term = extractLast(this.value);
                    if (term.length < 1) {
                        return false;
                    }
                },
                focus: function () { return false; },
                select: function (event, ui) {
                    var terms = split(this.value);
                    terms.pop();
                    terms.push(ui.item.value);
                    terms.push("");
                    this.value = terms.join(", ");
                    return false;
                }
            });
        });
        return this;
    };
})(jQuery)

String.prototype.trim = function () {
    return this.replace(/(^[\\s]*)|([\\s]*$)/g, "");
};

String.prototype.trimLeft = function () {
    return this.replace(/(^[\\s]*)/g, "");
};

String.prototype.trimRight = function () {
    return this.replace(/([\\s]*$)/g, "");
};